<template>
    <div>
        <h1>登录</h1>
        <div>
            <span>账号:</span>
            <input type="text" v-model="user.username" />
        </div>
        <div>
            <span>密码:</span>
            <input type="password" v-model="user.password" />
        </div>
        <button @click="login()">登录</button>
    </div>
</template>

<script>
import instance from '../utils/request';

export default {
    name: "Login",
    data() {
        return {
            user: [],
        };
    },
    methods: {
        login() {
            //发送 axios 请求到后端校验用户名和密码是否正确
            instance.post("/user/login",
                { username: this.user.username, password: this.user.password })
                .then((success) => {
                    console.log(success);
                    if (success.data.code == 200) {
                        //1.将 用户名 和 token 数据保存到 localStorage
                        localStorage.setItem("username", this.user.username);
                        localStorage.setItem("token", success.data.data);
                        //切换路由
                        this.$router.push({ name: 'Index' });
                    } else {
                        alert(success.data.data);
                    }
                });
        },
    },
};
</script>

<style scoped></style>
